<!-- templates/index.html -->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商店进销存管理系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/element-plus@2.3.8/dist/index.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/element-plus@2.3.8/dist/index.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>

    <!-- Tailwind 配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#0FC6C2',
                        success: '#00B42A',
                        warning: '#FF7D00',
                        danger: '#F53F3F',
                        info: '#86909C'
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                },
            }
        }
    </script>

    <!-- 自定义工具类 -->
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .sidebar-item {
                @apply flex items-center px-4 py-3 text-gray-600 hover:bg-gray-50 hover:text-primary transition-all duration-200;
            }
            .sidebar-item.active {
                @apply bg-primary/10 text-primary border-l-4 border-primary;
            }
            .card-shadow {
                @apply shadow-md hover:shadow-lg transition-shadow duration-300;
            }
        }
    </style>
</head>
<body class="font-inter bg-gray-50 min-h-screen flex flex-col">
<!-- 顶部导航栏 -->
<header class="bg-white shadow-sm">
    <div class="container mx-auto px-4 py-3 flex justify-between items-center">
        <div class="flex items-center space-x-2">
            <i class="fa fa-cubes text-primary text-2xl"></i>
            <h1 class="text-xl font-bold text-gray-800">商店进销存管理系统</h1>
        </div>

        <div class="flex items-center space-x-6">
            <div class="relative">
                <input type="text" placeholder="搜索..." class="pl-10 pr-4 py-2 rounded-full border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary">
                <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
            </div>

            <div class="flex items-center space-x-4">
                <button class="text-gray-600 hover:text-primary transition-colors">
                    <i class="fa fa-bell-o text-xl"></i>
                </button>
                <button class="text-gray-600 hover:text-primary transition-colors">
                    <i class="fa fa-cog text-xl"></i>
                </button>
                <div class="flex items-center space-x-2 cursor-pointer">
                    <img src="https://picsum.photos/200/200" alt="用户头像" class="w-8 h-8 rounded-full object-cover">
                    <span class="text-gray-700">管理员</span>
                </div>
            </div>
        </div>
    </div>
</header>

<div class="flex flex-1 overflow-hidden">
    <!-- 侧边栏导航 -->
    <aside class="w-64 bg-white shadow-md h-[calc(100vh-64px)] overflow-y-auto transition-all duration-300">
        <nav class="py-4">
            <div class="px-4 mb-4">
                <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">主菜单</h2>
            </div>

            <a href="index.html" class="sidebar-item active" data-path="index.html">
                <i class="fa fa-tachometer w-5 h-5 mr-3"></i>
                <span>仪表盘</span>
            </a>

            <div class="px-4 mt-6 mb-2">
                <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">基础信息</h2>
            </div>

            <a href="productlist.html" class="sidebar-item" data-path="productlist.html">
                <i class="fa fa-shopping-bag w-5 h-5 mr-3"></i>
                <span>商品管理</span>
            </a>

            <a href="categorylist.html" class="sidebar-item" data-path="categorylist.html">
                <i class="fa fa-th-large w-5 h-5 mr-3"></i>
                <span>类别管理</span>
            </a>

            <a href="supplierlist.html" class="sidebar-item" data-path="supplierlist.html">
                <i class="fa fa-truck w-5 h-5 mr-3"></i>
                <span>供应商管理</span>
            </a>

            <div class="px-4 mt-6 mb-2">
                <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">库存管理</h2>
            </div>

            <a href="warehouselist.html" class="sidebar-item"data-path="warehouselist.html">
                <i class="fa fa-archive w-5 h-5 mr-3"></i>
                <span>仓库管理</span>
            </a>

            <a href="inventorylist.html" class="sidebar-item" data-path="inventorylist.html">
                <i class="fa fa-list-alt w-5 h-5 mr-3"></i>
                <span>库存查询</span>
            </a>

            <a href="instock.html" class="sidebar-item" data-path="instock.html">
                <i class="fa fa-sign-in w-5 h-5 mr-3"></i>
                <span>入库管理</span>
            </a>

            <a href="outstock.html" class="sidebar-item " data-path="outstock.html">
                <i class="fa fa-sign-out w-5 h-5 mr-3"></i>
                <span>出库管理</span>
            </a>

            <a href="transfer.html" class="sidebar-item active" data-path="transfer.html">
                <i class="fa fa-exchange w-5 h-5 mr-3"></i>
                <span>转仓管理</span>
            </a>

            <div class="px-4 mt-6 mb-2">
                <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">统计分析</h2>
            </div>

            <a href="templates/statistics/sales.html" class="sidebar-item">
                <i class="fa fa-line-chart w-5 h-5 mr-3"></i>
                <span>销售统计</span>
            </a>

            <a href="templates/statistics/inventory.html" class="sidebar-item">
                <i class="fa fa-pie-chart w-5 h-5 mr-3"></i>
                <span>库存分析</span>
            </a>

            <div class="px-4 mt-6 mb-2">
                <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">系统设置</h2>
            </div>

            <a href="salesman.html" class="sidebar-item" data-path="salesman.html">
                <i class="fa fa-user-circle w-5 h-5 mr-3"></i>
                <span>用户管理</span>
            </a>


            <a href="backup.html" class="sidebar-item" data-path="system/logs.html">
                <i class="fa fa-history w-5 h-5 mr-3"></i>
                <span>数据库备份与恢复</span>
            </a>
        </nav>
    </aside>

    <!-- 主内容区域 -->
    <main class="flex-1 overflow-y-auto bg-gray-50 p-6">
        <div class="container mx-auto">
            <!-- 页面标题 -->
            <div class="mb-6">
                <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-gray-800">仪表盘</h2>
                <p class="text-gray-500 mt-1">欢迎使用商店进销存管理系统，今天是 <span id="current-date"></span></p>
            </div>

            <!-- 统计卡片 -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
                <div class="bg-white rounded-xl p-6 card-shadow">
                    <div class="flex justify-between items-start">
                        <div>
                            <p class="text-gray-500 text-sm">今日销售额</p>
                            <h3 class="text-3xl font-bold mt-1 text-gray-800" id="today-sales">--</h3>
                            <p class="text-success flex items-center mt-2 text-sm">
                                <i class="fa fa-arrow-up mr-1"></i> <span id="sales-change">--</span> <span class="text-gray-500 ml-1">较昨日</span>
                            </p>
                        </div>
                        <div class="p-4 bg-blue-100 rounded-lg">
                            <i class="fa fa-money text-primary text-2xl"></i>
                        </div>
                    </div>
                </div>

                <div class="bg-white rounded-xl p-6 card-shadow">
                    <div class="flex justify-between items-start">
                        <div>
                            <p class="text-gray-500 text-sm">今日订单数</p>
                            <h3 class="text-3xl font-bold mt-1 text-gray-800" id="today-orders">--</h3>
                            <p class="text-success flex items-center mt-2 text-sm">
                                <i class="fa fa-arrow-up mr-1"></i> <span id="orders-change">--</span> <span class="text-gray-500 ml-1">较昨日</span>
                            </p>
                        </div>
                        <div class="p-4 bg-green-100 rounded-lg">
                            <i class="fa fa-shopping-cart text-success text-2xl"></i>
                        </div>
                    </div>
                </div>

                <div class="bg-white rounded-xl p-6 card-shadow">
                    <div class="flex justify-between items-start">
                        <div>
                            <p class="text-gray-500 text-sm">库存总量</p>
                            <h3 class="text-3xl font-bold mt-1 text-gray-800" id="total-stock">--</h3>
                            <p class="text-danger flex items-center mt-2 text-sm">
                                <i class="fa fa-arrow-down mr-1"></i> <span id="stock-change">--</span> <span class="text-gray-500 ml-1">较昨日</span>
                            </p>
                        </div>
                        <div class="p-4 bg-purple-100 rounded-lg">
                            <i class="fa fa-cubes text-purple-500 text-2xl"></i>
                        </div>
                    </div>
                </div>

                <div class="bg-white rounded-xl p-6 card-shadow">
                    <div class="flex justify-between items-start">
                        <div>
                            <p class="text-gray-500 text-sm">库存预警</p>
                            <h3 class="text-3xl font-bold mt-1 text-gray-800" id="stock-warnings">--</h3>
                            <p class="text-warning flex items-center mt-2 text-sm">
                                <i class="fa fa-arrow-up mr-1"></i> <span id="warnings-change">--</span> <span class="text-gray-500 ml-1">较昨日</span>
                            </p>
                        </div>
                        <div class="p-4 bg-yellow-100 rounded-lg">
                            <i class="fa fa-exclamation-triangle text-warning text-2xl"></i>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 图表区域 -->
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
                <div class="bg-white rounded-xl p-6 card-shadow">
                    <div class="flex justify-between items-center mb-6">
                        <h3 class="font-semibold text-gray-800">销售趋势</h3>
                        <div class="flex space-x-2">
                            <button class="px-3 py-1 text-sm bg-primary text-white rounded-md">周</button>
                            <button class="px-3 py-1 text-sm bg-gray-100 text-gray-600 rounded-md">月</button>
                            <button class="px-3 py-1 text-sm bg-gray-100 text-gray-600 rounded-md">年</button>
                        </div>
                    </div>
                    <div class="h-80 flex items-center justify-center">
                        <div id="sales-chart-loader" class="text-center">
                            <div class="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
                            <p class="mt-4 text-gray-600">加载销售数据...</p>
                        </div>
                        <canvas id="salesChart" class="hidden"></canvas>
                    </div>
                </div>

                <div class="bg-white rounded-xl p-6 card-shadow">
                    <div class="flex justify-between items-center mb-6">
                        <h3 class="font-semibold text-gray-800">库存状态</h3>
                        <div class="flex space-x-2">
                            <button class="px-3 py-1 text-sm bg-primary text-white rounded-md">全部</button>
                            <button class="px-3 py-1 text-sm bg-gray-100 text-gray-600 rounded-md">预警</button>
                        </div>
                    </div>
                    <div class="h-80 flex items-center justify-center">
                        <div id="inventory-chart-loader" class="text-center">
                            <div class="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
                            <p class="mt-4 text-gray-600">加载库存数据...</p>
                        </div>
                        <canvas id="inventoryChart" class="hidden"></canvas>
                    </div>
                </div>
            </div>

            <!-- 最近操作和库存预警 -->
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                <div class="bg-white rounded-xl p-6 card-shadow lg:col-span-2">
                    <div class="flex justify-between items-center mb-6">
                        <h3 class="font-semibold text-gray-800">最近操作</h3>
                        <button class="text-primary text-sm">查看全部</button>
                    </div>
                    <div class="overflow-x-auto">
                        <div id="operations-loader" class="py-12 text-center">
                            <div class="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
                            <p class="mt-4 text-gray-600">加载操作记录...</p>
                        </div>
                        <table class="w-full hidden" id="recent-operations">
                            <thead>
                            <tr class="border-b border-gray-200">
                                <th class="py-3 text-left text-sm font-medium text-gray-500">操作类型</th>
                                <th class="py-3 text-left text-sm font-medium text-gray-500">商品名称</th>
                                <th class="py-3 text-left text-sm font-medium text-gray-500">数量</th>
                                <th class="py-3 text-left text-sm font-medium text-gray-500">操作人</th>
                                <th class="py-3 text-left text-sm font-medium text-gray-500">时间</th>
                            </tr>
                            </thead>
                            <tbody>
                            <!-- 最近操作数据将通过JavaScript动态填充 -->
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="bg-white rounded-xl p-6 card-shadow">
                    <div class="flex justify-between items-center mb-6">
                        <h3 class="font-semibold text-gray-800">库存预警</h3>
                        <button class="text-primary text-sm">查看全部</button>
                    </div>
                    <div class="space-y-4">
                        <div id="warnings-loader" class="py-8 text-center">
                            <div class="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
                            <p class="mt-4 text-gray-600">加载库存预警...</p>
                        </div>
                        <div id="stock-warnings-container" class="hidden">
                            <!-- 库存预警数据将通过JavaScript动态填充 -->
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>
</div>

<!-- 页脚 -->
<footer class="bg-white py-4 border-t border-gray-200">
    <div class="container mx-auto px-4 text-center text-gray-500 text-sm">
        <p>© 2025 商店进销存管理系统 - 版权所有</p>
    </div>
</footer>

<!-- JavaScript -->
<script>
    // API 配置 - 所有API都遵循相同的格式：http://localhost:8088/entity?page=0&size=10
    const API_CONFIG = {
        baseUrl: 'http://localhost:8088',
        endpoints: {
            products: '/product',
            instockOrders: '/inStockOrder',
            outstockOrders: '/outStockOrder',
            warehouses: '/warehouse',
            salesmen: '/salesman',
            // 假设这些API需要调整以匹配实际后端接口
            // dashboardStats: '/dashboard/stats',
            // recentOperations: '/operation',
            // stockWarnings: '/stockWarning',
            // salesTrend: '/dashboard/salesTrend'
            dashboardStats: '/api/stats.json',
            recentOperations: '/api/operation.json',
            stockWarnings: '/api/stockWarning.json',
            salesTrend: '/api/salesTrend.json'
        },
        defaultParams: {
            page: 0,
            size: 10
        }
    };

    // 全局数据存储
    let globalData = {
        products: [],
        instockOrders: [],
        outstockOrders: [],
        warehouses: [],
        salesmen: [],
        dashboardStats: {},
        recentOperations: [],
        stockWarnings: []
    };

    // 设置当前日期
    const setCurrentDate = () => {
        const now = new Date();
        const options = { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long' };
        document.getElementById('current-date').textContent = now.toLocaleDateString('zh-CN', options);
    };

    // 从API获取数据
    const fetchData = async (endpoint, params = {}) => {
        try {
            // 合并默认参数和传入参数
            const queryParams = new URLSearchParams({
                ...API_CONFIG.defaultParams,
                ...params
            });

            const url = `${API_CONFIG.baseUrl}${endpoint}?${queryParams}`;

            // 添加认证头（如果需要）
            const headers = {
                'Content-Type': 'application/json',
            };

            const response = await fetch(url, { headers });

            if (!response.ok) {
                //throw new Error(`HTTP error! Status: ${response.status}`);
            }

            const result = await response.json();

            // 检查业务状态码
            if (result.code !== 200) {
                //throw new Error(result.message || '获取数据失败');
            }

            return result.data;
        } catch (error) {
            console.error('Fetch error:', error);
            showGlobalError('数据加载失败，请稍后重试');
            throw error;
        }
    };

    // 显示全局错误提示
    const showGlobalError = (message) => {
        const errorContainer = document.createElement('div');
        errorContainer.className = 'fixed top-20 right-4 bg-danger text-white px-4 py-2 rounded-lg shadow-lg z-50 transform transition-all duration-300 translate-x-full';
        errorContainer.textContent = message;

        document.body.appendChild(errorContainer);

        // 显示错误提示
        setTimeout(() => {
            errorContainer.classList.remove('translate-x-full');
        }, 100);

        // 3秒后隐藏
        setTimeout(() => {
            errorContainer.classList.add('translate-x-full');
            setTimeout(() => {
                document.body.removeChild(errorContainer);
            }, 300);
        }, 3000);
    };

    // 初始化销售图表
    const initSalesChart = (salesData) => {
        const ctx = document.getElementById('salesChart').getContext('2d');

        document.getElementById('sales-chart-loader').classList.add('hidden');
        document.getElementById('salesChart').classList.remove('hidden');

        // 模拟销售趋势数据 - 实际应用中应从API获取
        const labels = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
        const salesAmount = [12500, 19000, 17000, 21000, 23000, 27000, 25000];
        const salesQuantity = [25, 40, 35, 42, 48, 55, 50];

        new Chart(ctx, {
            type: 'line',
            data: {
                labels: labels,
                datasets: [
                    {
                        label: '销售额(元)',
                        data: salesAmount,
                        borderColor: '#165DFF',
                        backgroundColor: 'rgba(22, 93, 255, 0.1)',
                        tension: 0.4,
                        fill: true
                    },
                    {
                        label: '销售量(件)',
                        data: salesQuantity,
                        borderColor: '#0FC6C2',
                        backgroundColor: 'rgba(15, 198, 194, 0.1)',
                        tension: 0.4,
                        fill: true
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'top',
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                let label = context.dataset.label || '';
                                if (label) {
                                    label += ': ';
                                }
                                if (context.dataset.label === '销售额(元)') {
                                    label += '¥' + context.parsed.y.toLocaleString();
                                } else {
                                    label += context.parsed.y + ' 件';
                                }
                                return label;
                            }
                        }
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            callback: function(value) {
                                if (this.datasetIndex === 0) {
                                    return '¥' + value.toLocaleString();
                                } else {
                                    return value + ' 件';
                                }
                            }
                        }
                    }
                }
            }
        });
    };

    // 初始化库存图表
    const initInventoryChart = (inventoryStatus) => {
        const ctx = document.getElementById('inventoryChart').getContext('2d');

        document.getElementById('inventory-chart-loader').classList.add('hidden');
        document.getElementById('inventoryChart').classList.remove('hidden');

        // 从库存数据中计算库存状态
        const productData = globalData.products;
        let sufficientCount = 0;    // 充足
        let lowStockCount = 0;       // 低库存
        let outOfStockCount = 0;     // 缺货
        let toReplenishCount = 0;    // 待补货

        // 假设库存预警阈值为50
        const warningThreshold = 50;

        productData.forEach(product => {
            if (product.productStock <= 0) {
                outOfStockCount++;
            } else if (product.productStock <= warningThreshold) {
                lowStockCount++;
            } else {
                sufficientCount++;
            }
        });

        // 待补货数量假设为低库存和缺货的总和
        toReplenishCount = lowStockCount + outOfStockCount;

        new Chart(ctx, {
            type: 'bar',
            data: {
                labels: ['充足', '低库存', '缺货', '待补货'],
                datasets: [
                    {
                        label: '商品数量',
                        data: [sufficientCount, lowStockCount, outOfStockCount, toReplenishCount],
                        backgroundColor: [
                            '#00B42A',
                            '#FF7D00',
                            '#F53F3F',
                            '#165DFF'
                        ]
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return context.parsed.y + ' 种商品';
                            }
                        }
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            callback: function(value) {
                                return value + ' 种';
                            }
                        }
                    }
                }
            }
        });
    };

    // 侧边栏切换
    const toggleSidebar = () => {
        const sidebar = document.querySelector('aside');
        sidebar.classList.toggle('w-64');
        sidebar.classList.toggle('w-20');

        const sidebarTexts = document.querySelectorAll('aside span');
        sidebarTexts.forEach(text => {
            text.classList.toggle('hidden');
        });
    };

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', async () => {
        setCurrentDate();
        initSidebarNavigation();
        setCurrentPageActive();

        try {
            // 并行获取数据
            const [productsResponse, instockOrdersResponse,outstockOrdersResponse, salesmenResponse, warehouseResponse] = await Promise.all([
                fetchData(API_CONFIG.endpoints.products),
                fetchData(API_CONFIG.endpoints.instockOrders),
                fetchData(API_CONFIG.endpoints.outstockOrders),
                fetchData(API_CONFIG.endpoints.salesmen),
                fetchData(API_CONFIG.endpoints.warehouses)
            ]);

            // 存储数据到全局变量
            globalData.products = productsResponse.content || [];
            globalData.instockOrders = instockOrdersResponse.content || [];
            globalData.outstockOrders = outstockOrdersResponse.content || [];
            globalData.salesmen = salesmenResponse.content || [];
            globalData.warehouses = warehouseResponse.content || [];

            // 计算仪表盘统计数据
            const dashboardStats = calculateDashboardStats();
            globalData.dashboardStats = dashboardStats;

            // 更新仪表盘统计数据
            updateDashboardStats(dashboardStats);

            // 初始化图表
            initSalesChart();
            initInventoryChart();

            // 渲染最近操作和库存预警
            const recentOperations = prepareRecentOperations();
            const stockWarnings = prepareStockWarnings();

            globalData.recentOperations = recentOperations;
            globalData.stockWarnings = stockWarnings;

            renderRecentOperations(recentOperations);
            renderStockWarnings(stockWarnings);
        } catch (error) {
            console.error('初始化失败:', error);
            // 显示错误状态
            document.getElementById('operations-loader').classList.add('hidden');
            document.getElementById('operations-error').classList.remove('hidden');
            document.getElementById('warnings-loader').classList.add('hidden');
            document.getElementById('warnings-error').classList.remove('hidden');
        }
    });

    /**
     * 初始化侧边栏导航
     */
    const initSidebarNavigation = () => {
        const sidebarItems = document.querySelectorAll('.sidebar-item');

        sidebarItems.forEach(item => {
            item.addEventListener('click', (e) => {
                e.preventDefault();

                const path = item.getAttribute('data-path');
                if (!path) return;

                // 更新激活状态
                updateActiveItem(item);

                // 显示加载指示器
                showPageLoader();

                // 使用平滑过渡加载新页面
                setTimeout(() => {
                    window.location.href = path;
                }, 300); // 动画持续时间
            });
        });
    };

    /**
     * 更新激活菜单项
     */
    const updateActiveItem = (activeItem) => {
        document.querySelectorAll('.sidebar-item').forEach(item => {
            item.classList.remove('active');
        });
        activeItem.classList.add('active');
    };

    /**
     * 设置当前页面菜单项为激活状态
     */
    const setCurrentPageActive = () => {
        const currentPath = window.location.pathname;
        const sidebarItems = document.querySelectorAll('.sidebar-item');

        sidebarItems.forEach(item => {
            const itemPath = item.getAttribute('data-path');
            if (itemPath && currentPath.endsWith(itemPath)) {
                updateActiveItem(item);
                return;
            }
        });
    };

    /**
     * 显示页面加载指示器
     */
    const showPageLoader = () => {
        const mainContent = document.querySelector('main');

        // 创建加载指示器元素
        const loader = document.createElement('div');
        loader.className = 'fixed inset-0 bg-white bg-opacity-80 flex items-center justify-center z-50';
        loader.innerHTML = `
            <div class="text-center">
                <div class="inline-block animate-spin rounded-full h-16 w-16 border-b-4 border-primary"></div>
                <p class="mt-4 text-xl font-medium text-gray-800">加载中...</p>
            </div>
        `;

        mainContent.appendChild(loader);
    };

    /**
     * 计算仪表盘统计数据
     */
    const calculateDashboardStats = () => {
        const products = globalData.products;
        const instockOrders = globalData.instockOrders;
        const outstockOrders = globalData.outstockOrders; // 假设出库数据在instockOrders中

        // 计算今日销售额 - 假设今天是2025-06-22
        const today = new Date();
        const todayDate = today.toISOString().split('T')[0];
        let todaySales = 0;
        let yesterdaySales = 15000; // 假设昨日销售额

        // 计算今日订单数
        const todayOrders = instockOrders.filter(order => {
            const orderDate = new Date(order.orderDate).toISOString().split('T')[0];
            return orderDate === todayDate;
        }).length;

        let yesterdayOrders = 8; // 假设昨日订单数

        // 计算库存总量
        const totalStock = products.reduce((sum, product) => sum + product.productStock, 0);

        // 计算较昨日库存变化 - 假设昨日库存为3000
        const yesterdayStock = 3000;
        const stockChange = ((totalStock - yesterdayStock) / yesterdayStock * 100).toFixed(1);

        // 计算库存预警数量 - 假设预警阈值为50
        const warningThreshold = 50;
        const stockWarnings = products.filter(product => product.productStock <= warningThreshold).length;

        // 计算较昨日预警变化 - 假设昨日预警数为5
        const yesterdayWarnings = 5;
        const warningsChange = ((stockWarnings - yesterdayWarnings) / yesterdayWarnings * 100).toFixed(1);

        return {
            todaySales: todaySales,
            salesChange: (todaySales > yesterdaySales ? '+' : '') + ((todaySales - yesterdaySales) / yesterdaySales * 100).toFixed(1),
            todayOrders: todayOrders,
            ordersChange: (todayOrders > yesterdayOrders ? '+' : '') + ((todayOrders - yesterdayOrders) / yesterdayOrders * 100).toFixed(1),
            totalStock: totalStock,
            stockChange: stockChange,
            stockWarnings: stockWarnings,
            warningsChange: warningsChange
        };
    };

    /**
     * 更新仪表盘统计数据
     */
    const updateDashboardStats = (stats) => {
        document.getElementById('today-sales').textContent = '¥' + stats.todaySales.toLocaleString();
        document.getElementById('sales-change').textContent = stats.salesChange + '%';
        document.getElementById('today-orders').textContent = stats.todayOrders;
        document.getElementById('orders-change').textContent = stats.ordersChange + '%';
        document.getElementById('total-stock').textContent = stats.totalStock;
        document.getElementById('stock-change').textContent = stats.stockChange + '%';
        document.getElementById('stock-warnings').textContent = stats.stockWarnings;
        document.getElementById('warnings-change').textContent = stats.warningsChange + '%';
    };

    /**
     * 准备最近操作数据
     */
    const prepareRecentOperations = () => {
        // 从入库和出库数据中提取最近操作
        const operations = [];

        // 创建商品ID到商品名称的映射表，使用productId作为键
        const productMap = {};
        globalData.products.forEach(product => {
            productMap[product.productId] = product.productName;
        });

        // 处理入库数据
        const instockOperations = globalData.instockOrders
            .filter(order => order.status === 'completed') // 只处理已完成的订单
            .flatMap(order => {
                // 将每个订单中的多个商品详情展开为多个操作记录
                return order.inStockDetails.map(detail => ({
                    type: '入库',
                    productId: detail.productId,
                    productName: productMap[detail.productId] || '未知商品',
                    quantity: detail.quantity || 0,
                    operator: globalData.salesmen.find(s => s.salesmanId === order.salesmanId)?.salesmanName || '未知操作人',
                    time: new Date(order.orderDate || Date.now()).toLocaleString(),
                    warehouse: globalData.warehouses.find(w => w.warehouseId === order.warehouseId)?.warehouseName || '未知仓库'
                }));
            });

        // 假设有出库数据 - 处理逻辑类似
        // 处理入库数据
        const outstockOperations = globalData.outstockOrders
            .filter(order => order.status === 'completed') // 只处理已完成的订单
            .flatMap(order => {
                // 将每个订单中的多个商品详情展开为多个操作记录
                return order.outStockDetails.map(detail => ({
                    type: '出库',
                    productId: detail.productId,
                    productName: productMap[detail.productId] || '未知商品',
                    quantity: detail.quantity || 0,
                    operator: globalData.salesmen.find(s => s.salesmanId === order.salesmanId)?.salesmanName || '未知操作人',
                    time: new Date(order.orderDate || Date.now()).toLocaleString(),
                    warehouse: globalData.warehouses.find(w => w.warehouseId === order.warehouseId)?.warehouseName || '未知仓库'
                }));
            });

        // 合并并按时间排序
        operations.push(...instockOperations, ...outstockOperations);
        operations.sort((a, b) => new Date(b.time) - new Date(a.time));

        // 取最近的10条记录
        return operations.slice(0, 10);
    };

    /**
     * 渲染最近操作数据
     */
    const renderRecentOperations = (operations) => {
        if (!operations || operations.length === 0) {
            document.getElementById('operations-loader').classList.add('hidden');
            document.getElementById('recent-operations').classList.add('hidden');
            document.getElementById('operations-empty').classList.remove('hidden');
            return;
        }

        const tableBody = document.querySelector('#recent-operations tbody');
        tableBody.innerHTML = '';

        operations.forEach(operation => {
            const row = document.createElement('tr');
            row.className = 'border-b border-gray-100 hover:bg-gray-50 transition-colors';

            // 设置行的颜色根据操作类型
            if (operation.type === '入库') {
                row.classList.add('text-success');
            } else if (operation.type === '出库') {
                row.classList.add('text-primary');
            } else if (operation.type === '转仓') {
                row.classList.add('text-purple-500');
            }

            row.innerHTML = `
                                <td class="py-3 px-4">${operation.type}</td>
                                <td class="py-3 px-4">${operation.productName}</td>
                                <td class="py-3 px-4">${operation.quantity}</td>
                                <td class="py-3 px-4">${operation.operator}</td>
                                <td class="py-3 px-4">${operation.time}</td>
                            `;

            tableBody.appendChild(row);
        });

        document.getElementById('operations-loader').classList.add('hidden');
        document.getElementById('recent-operations').classList.remove('hidden');
    };

    /**
     * 准备库存预警数据
     */
    const prepareStockWarnings = () => {
        const products = globalData.products;
        const warnings = [];

        // 假设库存预警阈值为50
        const warningThreshold = 50;

        products.forEach(product => {
            if (product.productStock <= warningThreshold) {
                warnings.push({
                    id: product.id,
                    name: product.productName,
                    stock: product.productStock,
                    threshold: warningThreshold,
                    warehouse: product.warehouseName || '未知仓库'
                });
            }
        });

        // 按库存数量排序（从低到高）
        warnings.sort((a, b) => a.stock - b.stock);

        return warnings;
    };

    /**
     * 渲染库存预警数据
     */
    const renderStockWarnings = (warnings) => {
        if (!warnings || warnings.length === 0) {
            document.getElementById('warnings-loader').classList.add('hidden');
            document.getElementById('stock-warnings-container').classList.add('hidden');
            document.getElementById('warnings-empty').classList.remove('hidden');
            return;
        }

        const container = document.getElementById('stock-warnings-container');
        container.innerHTML = '';

        warnings.forEach(warning => {
            const warningItem = document.createElement('div');
            warningItem.className = 'flex justify-between items-center p-3 border border-gray-100 rounded-lg hover:border-primary transition-colors';

            // 设置警告级别样式
            let warningLevel = 'bg-warning/10 border-warning/30';
            if (warning.stock <= 0) {
                warningLevel = 'bg-danger/10 border-danger/30';
            } else if (warning.stock <= warning.threshold / 2) {
                warningLevel = 'bg-warning/20 border-warning/40';
            }

            warningItem.className += ' ' + warningLevel;

            warningItem.innerHTML = `
                                <div class="flex items-center">
                                    <div class="w-10 h-10 rounded-full bg-gray-100 flex items-center justify-center mr-3">
                                        <i class="fa fa-exclamation-triangle text-warning"></i>
                                    </div>
                                    <div>
                                        <h4 class="font-medium text-gray-800">${warning.name}</h4>
                                        <p class="text-sm text-gray-500">仓库: ${warning.warehouse}</p>
                                    </div>
                                </div>
                                <div class="flex items-center space-x-4">
                                    <span class="text-sm font-medium ${warning.stock <= 0 ? 'text-danger' : 'text-warning'}">
                                        库存: ${warning.stock}
                                    </span>
                                    <button class="px-3 py-1 text-sm bg-primary text-white rounded-md hover:bg-primary/90 transition-colors">
                                        补货
                                    </button>
                                </div>
                            `;

            container.appendChild(warningItem);
        });

        document.getElementById('warnings-loader').classList.add('hidden');
        document.getElementById('stock-warnings-container').classList.remove('hidden');

    // 切换侧边栏
    document.getElementById('toggle-sidebar').addEventListener('click', toggleSidebar);
    };
</script>
</body>
</html>
